package com.hee.erp.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hee.erp.constant.ConstDictType;
import com.hee.erp.filter.LoginContextHolder;
import com.hee.erp.modules.entity.*;
import com.hee.erp.modules.mapper.BusCustomerMapper;
import com.hee.erp.modules.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hee.erp.modules.service.ICityService;
import com.hee.erp.modules.service.IProvinceService;
import com.hee.erp.vo.CommonListPageParamsVo;
import com.hee.erp.vo.CustomerListParamsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-04-16
 */
@Transactional
@Service
public class BusCustomerServiceImpl extends ServiceImpl<BusCustomerMapper, BusCustomer> implements IBusCustomerService {

    @Autowired
    IBusCustomerContactService customerContactService;

    @Autowired
    IBusCustomerBillingInfoService customerBillingInfoService;

    @Autowired
    IBusCustomer2UserService customer2UserService;

    @Autowired
    IBusCustomerVisitService customerVisitService;

    @Autowired
    ISysDictValueService dictValueService;

    @Autowired
    IProvinceService provinceService;

    @Autowired
    ICityService cityService;

    @Autowired
    ISysUserService sysUserService;


    @Override
    public Boolean saveDetail(BusCustomer customer) {
        Boolean isNew = false;
        //保存基本信息
        if (StringUtils.isBlank(customer.getId())) {
            //新增
            isNew = true;
            //自动生成客户编号
            String customerNo = generatorCustomerNo();
            customer.setCustomerNo(customerNo);
        }

        this.saveOrUpdate(customer);

        //保存联系人信息
        if (customer.getContactList() != null && customer.getContactList().size() > 0) {
            for (BusCustomerContact busCustomerContact : customer.getContactList()) {
                busCustomerContact.setCustomerId(customer.getId());
                customerContactService.saveOrUpdate(busCustomerContact);
            }
        }

        //保存开票信息
        if (customer.getBillingInfo() != null) {
            customer.getBillingInfo().setCustomerId(customer.getId());
            customerBillingInfoService.saveOrUpdate(customer.getBillingInfo());
        }

        //保存拜访记录
        if (customer.getVisitList() != null && customer.getVisitList().size() > 0) {
            for (BusCustomerVisit busCustomerVisit : customer.getVisitList()) {
                if (StringUtils.isBlank(busCustomerVisit.getId())) {
                    busCustomerVisit.setCustomerId(customer.getId());
                    customerVisitService.saveOrUpdate(busCustomerVisit);
                }
            }
        }

        if (isNew) {
            //如果是新增，当前登录人就是客户的负责人
            BusCustomer2User customer2User = new BusCustomer2User();
            customer2User.setCustomerId(customer.getId());
            customer2User.setUserId(LoginContextHolder.get().getUserId());
            customer2UserService.save(customer2User);
        } else {
            //保存负责人信息
            if (customer.getCustomerManagerList() != null && customer.getCustomerManagerList().size() > 0) {
                for (BusCustomer2User customer2User : customer.getCustomerManagerList()) {
                    if (StringUtils.isBlank(customer2User.getId())) {
                        customer2User.setCustomerId(customer.getId());
                        customer2UserService.saveOrUpdate(customer2User);
                    }
                }
            }
        }


        return true;
    }

    @Override
    public String generatorCustomerNo() {
        //获取当前最大的客户编号
        Integer maxCustomerNo = getMaxCustomerNo();
        String customerNo = "GY-" + String.format("%04d", maxCustomerNo + 1);
        return customerNo;
    }

    private Integer getMaxCustomerNo() {

        QueryWrapper<BusCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(customer_no) as customer_no");
        BusCustomer customer = this.getOne(queryWrapper);
        if (customer != null) {
            String customerNo = customer.getCustomerNo();
            //利用正则表达式，匹配出数字
            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(customerNo);
            if (matcher.find()) {
                return Integer.parseInt(matcher.group());
            }
        }
        return 0;
    }

    @Override
    public IPage<BusCustomer> listByPage(CustomerListParamsVo vo) {

        IPage<BusCustomer> page = new Page<>();
        page.setCurrent(vo.getCurrent());
        page.setSize(vo.getPageSize());

        QueryWrapper<BusCustomer> queryWrapper = createQueryWrapper(vo);

        this.page(page, queryWrapper);

        List<BusCustomer> records = page.getRecords();

        setForeignKey(records);

        return page;
    }

    private QueryWrapper<BusCustomer> createQueryWrapper(CustomerListParamsVo vo) {
        QueryWrapper<BusCustomer> queryWrapper = new QueryWrapper<>();
        //keyWords
        if (StringUtils.isNotBlank(vo.getKeyWords())) {
            queryWrapper.lambda().like(BusCustomer::getCustomerName, vo.getKeyWords());
        }

        //managerOrContactor
        if (StringUtils.isNotBlank(vo.getManagerOrContactor())) {
            //把两个集合合并
            List<String> customerIds = new ArrayList<>();

            //找到sys_user中姓名包含managerOrContactor的用户
            List<String> userIds = sysUserService.listUserIdByLikeName(vo.getManagerOrContactor());
            if (userIds != null && userIds.size() > 0) {
                //根据userIds查找到t_bus_customer_2_user 中的customerId
                List<String> managerCustomerIds = customer2UserService.listCustomerIdByUserIds(userIds);
                customerIds.addAll(managerCustomerIds);
            }


            //根据contact_name 找到t_bus_customer_contact中的customerId
            List<String> contactCustomerIds = customerContactService.listCustomerIdByLikeName(vo.getManagerOrContactor());
            customerIds.addAll(contactCustomerIds);

            //把customerIds放入queryWrapper
            if (customerIds != null && customerIds.size() > 0) {
                queryWrapper.lambda().in(BusCustomer::getId, customerIds);
            }else{
                //没有查到数据，查询不到数据
                queryWrapper.lambda().eq(BusCustomer::getId, "");
            }
        }

        //customerType
        if (vo.getCustomerType() != null) {
            queryWrapper.lambda().eq(BusCustomer::getCustomerType, vo.getCustomerType());
        }

        //managerId
        if (StringUtils.isNotBlank(vo.getManagerId())) {
            //根据managerId查找到t_bus_customer_2_user 中的customerId
            List<String> customerIds = customer2UserService.listCustomerIdsByUserId(vo.getManagerId());
            if(customerIds != null && customerIds.size() > 0){
                queryWrapper.lambda().in(BusCustomer::getId, customerIds);
            }else{
                //没有查到数据，查询不到数据
                queryWrapper.lambda().eq(BusCustomer::getId, "");
            }
        }
        return queryWrapper;

    }

    private void setForeignKey(List<BusCustomer> records) {

        records.forEach(customer -> {
            //设置客户类型
            if (customer.getCustomerType() != null) {
                SysDictValue dictValue = dictValueService.getByTypeAndValue(ConstDictType.CUSTOMER_TYPE, customer.getCustomerType());
                customer.setCustomerTypeName(dictValue.getDictName());
            }
            //设置provinceName
            if (customer.getProvinceId() != null) {
                Province province = provinceService.getById(customer.getProvinceId());
                customer.setProvinceName(province.getName());
            }
            //设置cityName
            if (customer.getCityId() != null) {
                City city = cityService.getById(customer.getCityId());
                customer.setCityName(city.getName());
            }
            //设置纳税类型
            if (customer.getPayTaxType() != null) {
                SysDictValue dictValue = dictValueService.getByTypeAndValue(ConstDictType.PAY_TAX_TYPE, customer.getPayTaxType());
                customer.setPayTaxTypeName(dictValue.getDictName());
            }
            //设置创建人
            SysUser createUser = sysUserService.getById(customer.getCreateUser());
            customer.setCreateUserName(createUser.getUserName());

            //设置负责人
            List<BusCustomer2User> contactList = customer2UserService.getListByCustomerId(customer.getId());
            customer.setCustomerManagerList(contactList);

        });

    }

    @Override
    public BusCustomer getDetailById(String id) {
        BusCustomer customer = this.getById(id);
        //客户类型
        if (customer.getCustomerType() != null) {
            SysDictValue dictValue = dictValueService.getByTypeAndValue(ConstDictType.CUSTOMER_TYPE, customer.getCustomerType());
            if (dictValue != null) {
                customer.setCustomerTypeName(dictValue.getDictName());
            }
        }
        //纳税类型
        if (customer.getPayTaxType() != null) {
            SysDictValue dictValue = dictValueService.getByTypeAndValue(ConstDictType.PAY_TAX_TYPE, customer.getPayTaxType());
            if (dictValue != null) {
                customer.setPayTaxTypeName(dictValue.getDictName());
            }
        }

        //省
        if (customer.getProvinceId() != null) {
            Province province = provinceService.getById(customer.getProvinceId());
            customer.setProvinceName(province.getName());
        }
        //市
        if (customer.getCityId() != null) {
            City city = cityService.getById(customer.getCityId());
            customer.setCityName(city.getName());
        }

        //客户联系人
        List<BusCustomerContact> contactList = customerContactService.getListByCustomerId(customer.getId());
        customer.setContactList(contactList);

        //客户开票信息
        BusCustomerBillingInfo billingInfo = customerBillingInfoService.getByCustomerId(customer.getId());
        customer.setBillingInfo(billingInfo);

        //客户拜访记录
        List<BusCustomerVisit> visitList = customerVisitService.getListByCustomerId(customer.getId());
        customer.setVisitList(visitList);

        //客户负责人
        List<BusCustomer2User> principalList = customer2UserService.getListByCustomerId(customer.getId());
        customer.setCustomerManagerList(principalList);

        return customer;
    }
}
